<?php
if (!defined("APP_PATH")) {
    define('APP_PATH', __DIR__ . '/../application/');
    // 加载框架引导文件
    require __DIR__ . '/../thinkphp/start.php';
}

use think\Db;
use think\Exception;
use think\Log;
use fast\Http;

echo "<pre>";
set_time_limit(0);


//每2分钟触发一次
while (true) {
    get_order_result();
    sleep(120);
}


function get_order_result()
{
    $test = false;
    $debug = config("app_debug");

    if (php_sapi_name() != 'cli' && !$debug) {
        // echo '只能在cli模式下或者开启调试模式运行：' . date('Y-m-d H:i:s') . "\r\n";die;
    }

    echo '开始执行的时间：' . date('Y-m-d H:i:s') . "\r\n";

    $redis = rds();
    $bkey = 'get_order_result';
    if ($debug)
        delkey($redis, $bkey);
    $op = $redis->set($bkey, 1, ['NX', 'EX' => 120]);
    if (!$op) {
        echo '请勿频繁操作：' . date('Y-m-d H:i:s') . "\r\n";
        goto END1;
    }

    $prefix = config('database.prefix');
    $time = time();
//    $d = date('Ymd');
    $orders = \db('tron_order')->alias('o')
        ->join('user_detail ud', 'ud.uid = o.uid')
        ->where('o.status', 0)
        ->column('o.id,o.uid,o.type,o.amt,o.txid,ud.tjstr,o.use_available', 'o.id');
    if (!empty($orders)) {
        $tz_frozen_users = [];
        $tz_frozen = [];//会员投资额度释放冻结资产
        $investments = [];//会员投资额度
        $withdrawals = [];//会员提现失败总金额
        $withdrawals_available = [];//提现失败-可提的数量
        $add_inv = 0;//矿池余额增加(投资)
        $to_status = '';
        $oids = '';
        $url = config('transaction')['fullNode_url'] . '/wallet/gettransactionbyid';
        $pvArrays = []; //小区业绩
        foreach ($orders as $order_key => $order) {

            if (empty($order['txid'])) continue;

            if (!$test) {
                $result = Http::post($url, json_encode(['value' => $order['txid']]));
                if ($result == '') continue;
                $result = json_decode($result, 1);
            } else {
                //全部成功
                $result['ret'] = [];
                $result['ret'][0] = [];
                $result['ret'][0]['contractRet'] = 'SUCCESS';

                //部分成功
//                $result = [];
//                if($order_key % 2) {
//                    $result['Error'] = "error";
//                } else {
//                    $result['ret'] = [];
//                    $result['ret'][0] = [];
//                    $result['ret'][0]['contractRet'] = 'SUCCESS';
//                }
            }

            if (!empty($result['ret'][0]['contractRet']) && $result['ret'][0]['contractRet'] == 'SUCCESS') {//交易结果为成功

                //如果金额不一致则返回
                if($result['raw_data']['contract'][0]['parameter']['value']['amount'] / 1000000 != $order['amt']) {
                    Log::error("order exception：amt". $order['id']);
                    continue;
                }

                $address = $result['raw_data']['contract'][0]['parameter']['value']['to_address'];

                if($address != "4109beb812564ad2c574866a286e77945853eca1fd") {
                    Log::error("order exception：address". $order['id']);
                    continue;
                }

                $to_status .= " when id={$order['id']} then 1 ";
                $oids .= ",{$order['id']}";
                if ($order['type'] == 0) {//投资
                    $add_inv += $order['amt'];
                    $tz_frozen_users[$order['uid']] = isset($tz_frozen_users[$order['uid']]) ? $tz_frozen_users[$order['uid']] + 1 : 1;

                    if (empty($investments[$order['uid']])) {
                        $investments[$order['uid']] = $order['amt'];
                        $tz_frozen[$order['uid']] = $order['amt'];
                    } else {
                        $investments[$order['uid']] += $order['amt'];
                        $tz_frozen[$order['uid']] += $order['amt'];
                    }
                    $new_tjstr = $order['uid'] . "," . $order['tjstr'];
                    $tjstr_arr = explode(',', $new_tjstr);
                    foreach ($tjstr_arr as $value) {
                        if (empty($pvArrays[$value])) {
                            $pvArrays[$value] = $order['amt'];
                        } else {
                            $pvArrays[$value] += $order['amt'];
                        }
                    }

                } else {//提现

                }
            } elseif (!empty($result['Error']) || (!empty($result['ret'][0]['contractRet']) && ($result['ret'][0]['contractRet'] == 'REVERT' || $result['ret'][0]['contractRet'] == 'OUT_OF_ENERGY'))) {//交易结果为失败
                $to_status .= " when id={$order['id']} then 2 ";
                $oids .= ",{$order['id']}";
                if ($order['type'] == 1) {//提现失败
                    if (empty($withdrawals[$order['uid']])) {
                        $withdrawals[$order['uid']] = $order['amt'];
                        $withdrawals_available[$order['uid']] = $order['use_available'];
                    } else {
                        $withdrawals[$order['uid']] += $order['amt'];
                        $withdrawals_available[$order['uid']] += $order['use_available'];
                    }
                }
            }
        }
        unset($orders);
        if ($to_status) {
            $oids = trim($oids, ',');
            $to_status = "UPDATE {$prefix}tron_order SET status=(case {$to_status} else status end),updatetime=(case when id in ({$oids}) then '{$time}' else updatetime end)";
        }

        $u_credit1 = '';
        $u_credit2 = '';
        $u_credit6 = '';

        $credit1 = [];

        foreach ($investments as $uid => $investment) {
            if (empty($credit1[$uid])) {
                $credit1[$uid] = $investment;
            } else {
                $credit1[$uid] += $investment;
            }
        }

        foreach ($withdrawals as $uid => $investment) {
            if (empty($credit1[$uid])) {
                $credit1[$uid] = $investment;
            } else {
                $credit1[$uid] += $investment;
            }
        }

        foreach ($credit1 as $k => $v) {
            if ($v > 0) {
                $u_credit1 .= " when id={$k} then credit1+{$v} "; //总余额
            }
        }

        //会员投资额度增长
        if ($investments) {
            foreach ($investments as $uid => $investment) {
                if ($investment > 0) {
                    $u_credit2 .= " when id={$uid} then credit2+{$investment} "; //充值的
                }
            }
        }

        //返还提现余额
        if ($withdrawals) {
            foreach ($withdrawals_available as $uid => $withdrawal) {
                $u_credit6 .= " when id={$uid} then credit6+{$withdrawal}";
            }
        }

        $u_pv = '';
        $u_pv_sum = '';
        //小区业绩
        if ($pvArrays) {
            foreach ($pvArrays as $uid => $pv) {
                if ($pv > 0) {
                    $u_pv .= " when id={$uid} then pv+{$pv} ";
                    $u_pv_sum .= " when id={$uid} then pv_sum+{$pv} ";
                }
            }
        }

        unset($withdrawals);
        $u_update = '';
        if ($u_credit1) {
            $u_update = " credit1=(case {$u_credit1} else credit1 end)";
        }

        if ($u_credit2) {
            $u_update .= ",credit2=(case {$u_credit2} else credit2 end)";
        }
        if ($u_pv) {
            $u_update .= ",pv=(case {$u_pv} else pv end)";
        }
        if ($u_pv_sum) {
            $u_update .= ",pv_sum=(case {$u_pv_sum} else pv_sum end)";
        }

        if ($u_credit6) {
            $u_update .= ",credit6=(case {$u_credit6} else credit6 end)";
        }



        db::startTrans();
        try {
            if ($to_status) \db()->execute($to_status);
            if ($u_update) \db()->execute("UPDATE {$prefix}user SET " . trim($u_update, ','));

            if ($investments && config("site.run_switch")) {
                \app\common\core\BonusSettle::rechargeReward($investments, $redis);
            }

            db::commit();
        } catch (\Exception $e) {
            db::rollback();
            Log::error($e->getMessage());
            echo $e->getFile()."(".$e->getLine().")".$e->getMessage();
            echo '执行失败：' . date('Y-m-d H:i:s') . "\r\n";
        }

    } else {
        echo '没有需要获取结果的订单：' . date('Y-m-d H:i:s') . "\r\n";
    }

//    END2:
    delkey($redis, $bkey);
    END1:
    echo "\r\n" . '结束执行的时间：' . date('Y-m-d H:i:s') . "\r\n";
}


